// packageA/pages/ViewerLetter/VIewerLetter.js
const app = getApp()
const {
  requestDataparams
} = require('../../../utils/request.js');
var applet_park_api_url_imgUrl = app.globalData.applet_park_api_url_imgUrl;
var applet_park_api_url = app.globalData.applet_park_api_url;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userId: '',
    userPhone: '',
    startTime: '',
    endTime: '',
    imgUrl: applet_park_api_url_imgUrl,
    chooseList: [
      '面试', '开会', '拜访'
    ],
    activeIndex: 0,
    top: 0,
    height: 0,
    detailInfo: {
      pic1: null,
      pic2: null,
    },
    phoneNumber: '',
    visitorPhone: '',
    type: 1,
    phoneUseful: true,
    nickName:''
  },
  goBack() {
    wx.navigateBack({
      delta: 1
    })
  },
  choosetype(e) {
    let activeIndex = e.currentTarget.dataset.i
    this.setData({
      activeIndex
    })

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.userId) {
      this.setData({
        userId: options.userId,
        type: 2,
      })
    }
    console.log(options)
    if (options.userPhone) {
      this.setData({
        userPhone: options.userPhone,
        phoneNumber: options.userPhone,
        startTime: options.startTime,
        endTime: options.endTime,
        nickName: options.nickName
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  // 验证访客手机号
  visitorChange(e) {
    let value = e.detail.value
    // value.test()
    let rxp = new RegExp("^[0-9]*$")
    let m = rxp.test(value)
    if (!m) {
      wx.showToast({
        title: '请输入数字',
        icon: 'none'
      })
      this.setData({
        visitorPhone: ''
      })
      return
    }
    this.setData({
      visitorPhone: value
    })
  },
  // 检验手机号是否备案
  testPhone(e) {
    let phoneNumber = e.detail.value
    let rxp = new RegExp("^[0-9]*$")
    let m = rxp.test(phoneNumber)
    if (!m) {
      wx.showToast({
        title: '请输入数字',
        icon: 'none'
      })
      this.setData({
        phoneNumber: '',
        phoneUseful: true
      })
      return
    }
    if (phoneNumber.length < 10) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      })
      return
    }
    let _this = this
    wx.request({
      url: applet_park_api_url + '/api/sysUsers/validatePhone',
      data: {
        phoneNumber: phoneNumber
      },
      method: "GET",
      success: function (res) {
        if (res.data.code == 1) {
          wx.showToast({
            title: res.data.message,
            icon: 'none'
          })
          _this.setData({
            phoneNumber: ''
          })
        }
      }
    })

  },
  //  表单提交
  bindsubmit(e) {
    let formInfo = e.detail.value
    let wxOpenId = wx.getStorageSync("OPENID")
    if (!formInfo.visitorName.length) {
      wx.showToast({
        title: '请输入访客姓名',
        icon: 'none'
      })
      return
    }
    if (!formInfo.visitorPhone.length) {
      wx.showToast({
        title: '请输入访客电话',
        icon: 'none'
      })
      return
    }
    if (!formInfo.content.length) {
      wx.showToast({
        title: '请输入访客事宜',
        icon: 'none'
      })
      return
    }
    if (!formInfo.phoneNumber.length) {
      wx.showToast({
        title: '请输入被访人电话',
        icon: 'none'
      })
      return
    }
    if (this.data.faceImage == '') {
      wx.showToast({
        title: '请上传面部识别照片',
        icon: 'none'
      })
      return
    }
    if (this.data.visitorPhone == formInfo.phoneNumber) {
      wx.showToast({
        title: '被访人电话与访客电话不可相同',
        icon: 'none'
      })
      return
    }
    if (this.data.phoneUseful == false) {
      wx.showToast({
        title: '被访人电话未备案',
        icon: 'none'
      })
      return
    }
    wx.request({
      url: applet_park_api_url + '/api/visitors/visitorJurisdiction',
      method: "POST",
      data: {
        phoneNumber: formInfo.phoneNumber
      },
      success: function (res) {
        console.log(res)
        if (res.data.code == 1) {
          wx.showToast({
            title: '被访人无被访权限！',
            icon: 'none'
          })
          return
        }
      }
    })
    requestDataparams('/api/visitorLetters', {
        visitorName: formInfo.visitorName,
        visitorPhone: formInfo.visitorPhone,
        visitorWxOpenId: wxOpenId,
        content: formInfo.content,
        userPhone: formInfo.phoneNumber,
        faceImage: this.data.faceImage,
        type: this.data.type,
        visitStartTime: this.data.startTime,
        visitEndTime: this.data.endTime
      },
      'POST', 'sign').then(response => {
      if (response.data.code == 0) {
        wx.showToast({
          title: '申请成功',
          icon: 'success'
        })
        var pages = getCurrentPages();
        var prevPage = pages[pages.length - 2]; //上一个页面
        prevPage.initPage()
        wx.navigateBack({
          delta: 1
        })

      } else {
        wx.showToast({
          title: '用户信息错误，请重新填写',
          icon: 'none'
        })
      }
    }).catch(err => {

    })
  },
  chooseImage: function (e) {
    var that = this;
    let pic = e.currentTarget.dataset.pic;
    wx.chooseImage({
      count: 1,
      success: function (res) {
        that.data.detailInfo[pic] = res.tempFiles[0];

        that.setData({
          detailInfo: that.data.detailInfo
        });
        that.imgUpLoad()
      }
    })
  },
  //  图片上传
  imgUpLoad() {
    wx.showLoading({
      title: '图片上传中',
    })
    var that = this;
    const detailInfo = that.data.detailInfo;
    // for (var idx = 1; idx <= ; idx++) {
    let file = detailInfo['pic' + 1];
    if (file && file.path) {
      wx.uploadFile({
        url: applet_park_api_url + '/api/upload',
        filePath: file.path,
        name: 'files',
        success: function (res) {
          const response = JSON.parse(res.data)
          if (response.code == 0) {
            that.setData({
              faceImage: response.data
            })
            wx.hideLoading();
          } else {
            wx.showToast({
              title: '图片上传失败',
            })
            wx.hideLoading();
          }

        },
        fail: function (err) {
          wx.hideLoading();
        }
      })
    }
    // }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let top = app.globalData.navTop
    let height = app.globalData.navHeight
    this.setData({
      top,
      height
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})